﻿<%@ WebHandler Language="C#" Class="UnqualifiedReasonSpec" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 工序不合格原因报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:longbin
 * Date:
 **/

public class UnqualifiedReasonSpec : IHttpHandler
{
    private uMESReportOracleDAL dal = new uMESReportOracleDAL();
    private UserImage u = new UserImage();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询方法
    Result getData(JObject jObject)
    {
        Result r = new Result();
        var sql = getSQL(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataRow row in dt.Rows)
        {
            DataTable dtt = dal.GetDataTable(string.Format("SELECT to_char(wm_concat(UNQUALIFIEDFEATURENAME)) UNQUALIFIEDFEATURE FROM UNQUALIFIEDFEATURE WHERE UNQUALIFIEDFEATUREID IN('{0}')", row["unqualifiedfeatureids"].ToString().Replace(",", "','")));
            row["UNQUALIFIEDFEATURE"] = dtt.Rows[0]["UNQUALIFIEDFEATURE"];
        }
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSQL(jObject);

        DataTable dt = dal.GetDataTable(sql);
        foreach (DataRow row in dt.Rows)
        {
            DataTable dtt = dal.GetDataTable(string.Format("SELECT to_char(wm_concat(UNQUALIFIEDFEATURENAME)) UNQUALIFIEDFEATURE FROM UNQUALIFIEDFEATURE WHERE UNQUALIFIEDFEATUREID IN('{0}')", row["unqualifiedfeatureids"].ToString().Replace(",", "','")));
            row["UNQUALIFIEDFEATURE"] = dtt.Rows[0]["UNQUALIFIEDFEATURE"];
        }
        dt.Columns.Remove("unqualifiedfeatureids");
        dt.Columns["mfgordername"].Caption = "生产订单";
        dt.Columns["containername"].Caption = "件号/批次号";
        dt.Columns["productname"].Caption = "件号名称";
        dt.Columns["productrevision"].Caption = "件号版本";
        dt.Columns["workflowinfo"].Caption = "工艺版次";
        dt.Columns["specno"].Caption = "工序号";
        dt.Columns["workflowstepname"].Caption = "工序名称";
        dt.Columns["operator"].Caption = "操作者";
        dt.Columns["reportdate"].Caption = "报工时间";
        dt.Columns["checkername"].Caption = "检验员";
        dt.Columns["checkdate"].Caption = "检验时间";
        dt.Columns["reworkqty"].Caption = "返修数";
        dt.Columns["unqualifiedfeature"].Caption = "不合格特征";
        dt.Columns["unqualifiedreasoncode"].Caption = "不合格原因代码";
        dt.Columns["gongyiyuan"].Caption = "工艺员";
        ExportHelper.ExportExcel(dt, "工序不合格原因报表");
    }

    private string getSQL(JObject jObject)
    {
        string sql = @"
select c2.mfgordername,c2.containername,c2.productname,c2.productrevision,c2.productdescription,c2.workflowname ||':'||c2.workflowrevision workflowinfo
,w.workflowstepname,nvl(s.specno,s3.specno) specno,e2.fullname operator,e.fullname checkername,c.createdate checkDate,c.reworkqty,c.unqualifiedfeatureids,null unqualifiedfeature,c.unqualifiedreasoncode 
,c3.createdate reportdate,e3.fullname gongyiyuan
from containercheckinfo c
left join containercurrentinfo c2 on c2.containerid =c.containerid 
left join workflowstep w on w.workflowstepid =c.workflowstepid
left join spec s on s.specid =w.specid
left join specbase s2 on s2.specbaseid =w.specbaseid 
left join spec s3 on s3.specbaseid =s2.specbaseid and s3.specid =s2.revofrcdid 
left join employee e on e.employeeid =c.checkerid
left join employee e2 on e2.employeeid =c.unqualifiedreasoncodeempid 
left join containerstepworkreport c3 on c3.containerstepworkreportid =c.containerstepworkreportid 
left join employee e3 on e3.employeeid =c2.techniqueemployeeid 
where c.unqualifiedfeatureids is not null ";
        // 分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND c2.originalfactoryid = '{0}'", jObject["factoryid"].ToString());
        }

        // 检验时间
        if (jObject["checkDate"] != null && jObject["checkDate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["checkDate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND c.createdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss') ", arr[0].ToString());
                sql += string.Format(" AND c.createdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss') ", arr[1].ToString());
            }
        }

        // 操作者
        if (jObject["operator"] != null && jObject["operator"].ToString() != "")
        {
            sql += string.Format(" AND e2.fullname like '%{0}%'", jObject["operator"].ToString());
        }

        // 检验员
        if (jObject["jianyanyuan"] != null && jObject["jianyanyuan"].ToString() != "")
        {
            sql += string.Format(" AND c.checkerid='{0}'", jObject["jianyanyuan"].ToString());
        }

        // 工艺员
        if (jObject["gongyiyuan"] != null && jObject["gongyiyuan"].ToString() != "")
        {
            sql += string.Format(" AND c2.techniqueemployeeid = '{0}'", jObject["gongyiyuan"].ToString());
        }

        // 机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND c2.familylistnames LIKE '%{0}%'", jObject["productfamilyname"].ToString());
        }

        // 批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND c2.containername like '%{0}%'", jObject["containername"].ToString());
        }

        if (jObject["specno"] != null && jObject["specno"].ToString() != "")
        {
            sql += string.Format(" AND nvl(s.specno,s3.specno) like '%{0}%'", jObject["specno"].ToString());
        }
        //不合格特征
        if (jObject["unqualifiedfeature"] != null && jObject["unqualifiedfeature"].ToString() != "")
        {
            DataTable udt = dal.GetDataTable(string.Format("SELECT u.UNQUALIFIEDFEATUREID FROM UNQUALIFIEDFEATURE u WHERE u.UNQUALIFIEDFEATURENAME LIKE '%{0}%'", jObject["unqualifiedfeature"].ToString()));
            var unqualifiedfeatureids = string.Empty;
            if (udt.Rows.Count > 0)
            {
                foreach (DataRow row in udt.Rows)
                {
                    unqualifiedfeatureids += " c.unqualifiedfeatureids like '%" + row["UNQUALIFIEDFEATUREID"] + "%' or";
                }
            }
            if (!string.IsNullOrWhiteSpace(unqualifiedfeatureids))
            {
                sql += "and (" + unqualifiedfeatureids.TrimEnd('r').TrimEnd('o') + ")";
            }
            else
            {
                sql += "and c.unqualifiedfeatureids like '%" + jObject["unqualifiedfeature"].ToString() + "%'";
            }
        }
        //不合格原因代码
        if (jObject["unqualifiedreasoncode"] != null && jObject["unqualifiedreasoncode"].ToString() != "")
        {
            sql += string.Format(" AND c.unqualifiedreasoncode like '%{0}%'", jObject["unqualifiedreasoncode"].ToString());
        }
        return sql;
    }
    
}